package com.sxygsj.baselibrary.network

import com.sxygsj.baselibrary.network.netInterface.ProgressObserver
import okhttp3.MediaType
import okhttp3.RequestBody
import okio.*
import java.io.File
import java.io.IOException

/**
 * @Author LD
 * @Time 2021/3/4 15:25
 * @Describe 单个文件上传封装的RequestBody，用于观察进度
 * @Modify
 */
open class UploadFileRequestBody(contentType: MediaType?, file: File,_progressObserver: ProgressObserver) : RequestBody() {

    private val mRequestBody: RequestBody = create(contentType, file)
    var progressObserver: ProgressObserver = _progressObserver


    override fun contentType(): MediaType? {
        return mRequestBody.contentType()
    }

    @Throws(IOException::class)
    override fun writeTo(sink: BufferedSink) {
        val countingSink =
            CountingSink(sink)
        val bufferedSink = Okio.buffer(countingSink)
        //写入
        mRequestBody.writeTo(bufferedSink)
        //刷新
        //必须调用flush，否则最后一部分数据可能不会被写入
        bufferedSink.flush()
    }

    @Throws(IOException::class)
    override fun contentLength(): Long {
        return mRequestBody.contentLength()
    }

    protected inner class CountingSink(delegate: Sink?) : ForwardingSink(delegate) {
        //已经写的bytes字节
        private var bytesWritten: Long = 0

        @Throws(IOException::class)
        override fun write(source: Buffer, byteCount: Long) {
            super.write(source, byteCount)
            bytesWritten += byteCount
            // TODO: 2021/3/4 看这里如何设置byteCount，人为定义一次写入的字节数

            progressObserver.onProgress((100 * bytesWritten / contentLength()).toInt())
        }
    }


}